package top.songxs.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import top.songxs.yygh.common.exp.DiyException;
import top.songxs.yygh.hosp.repository.DepartmentRepository;
import top.songxs.yygh.hosp.repository.HospitalRepository;
import top.songxs.yygh.hosp.repository.ScheduleRepository;
import top.songxs.yygh.hosp.service.DepartmentService;
import top.songxs.yygh.hosp.service.HospitalService;
import top.songxs.yygh.hosp.service.ScheduleService;
import top.songxs.yygh.hosp.util.AckUtil;
import top.songxs.yygh.model.hosp.BookingRule;
import top.songxs.yygh.model.hosp.Hospital;
import top.songxs.yygh.model.hosp.Schedule;
import top.songxs.yygh.vo.hosp.BookingScheduleRuleVo;
import top.songxs.yygh.vo.hosp.ScheduleOrderVo;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    DepartmentRepository departmentRepository;
    @Autowired
    ScheduleRepository scheduleRepository;
    @Autowired
    HospitalRepository hospitalRepository;
    @Autowired
    AckUtil ackUtil;

    @Override
    public void saveSchedule(Map<String, String> map) {
        // 权限校验  签名校验
        ackUtil.AckSign(map);
        //  从mg查询排版看是否已经有了
        // 转换对象
        String s = JSON.toJSONString(map);
        Schedule schedule = JSON.parseObject(s, Schedule.class);
        Schedule scheduleFromMG = scheduleRepository.findByHoscodeAndDepcodeAndHosScheduleId(schedule.getHoscode(), schedule.getDepcode(), schedule.getHosScheduleId());
        if (scheduleFromMG == null) {
            //如果没有则为新增
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        } else {
            //如果有则为修改
            schedule.setId(scheduleFromMG.getId());
            schedule.setCreateTime(scheduleFromMG.getCreateTime());
            schedule.setUpdateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> showDepartments(Map<String, String> map) {
        ackUtil.AckSign(map);

        String hoscode = map.get("hoscode");
        String depcode = map.get("depcode");
        String page = map.get("page");
        String limit = map.get("limit");

        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        schedule.setDepcode(depcode);


        Pageable pageable = PageRequest.of(Integer.parseInt(page) - 1, Integer.parseInt(limit), Sort.by(Sort.Direction.DESC, "createTime"));


        Example<Schedule> example = Example.of(schedule);
        Page<Schedule> pageResult = scheduleRepository.findAll(example, pageable);
        return pageResult;
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {

        //当前的日期
        //分组聚合
        BookingRule bookRule = hospitalRepository.getByHoscode(hoscode).getBookingRule();

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> pageResult = this.getPageDateTime(page, limit, bookRule);
        List<Date> pageDateList = pageResult.getRecords();

        long pages = pageResult.getPages();//总页数
        long total = pageResult.getTotal();//总日期数


        Criteria criteria = Criteria
                .where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(pageDateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria), //针对哪些排班统计
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                        .first("workDate").as("workDateMd")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> list = aggregate.getMappedResults();
        //将list转换为一个map并且 key是workDate value是BookingScheduleRuleVo对象
        //然后根据key获取value判断是否存在不存在就创建默认的对象
        Map<Date, BookingScheduleRuleVo> map = list.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        List<BookingScheduleRuleVo> bookingScheduleList = new ArrayList<>();
        for (int i = 0; i < pageDateList.size(); i++) {
            Date date = pageDateList.get(i);
            BookingScheduleRuleVo item = map.get(date);
            if (item == null) {
                item = new BookingScheduleRuleVo();
                item.setWorkDate(date);
                item.setWorkDateMd(date);
                item.setAvailableNumber(-1);
                item.setReservedNumber(-1);
                item.setDocCount(-1);
            }
            item.setDayOfWeek(this.dayOfWeek(date));
            //	@ApiModelProperty(value = "状态 0：正常 1：即将放号 -1：当天已停止挂号")  判断第一页第一条当天是否已经停止挂号，如果已经停止挂号就把他设置为-1
            //如果是最后一页的最后一条 则设置为1 即将放号 ，其他 rulevo的status统一设置为0
            item.setStatus(0);
            if (page == 1 && i == 0) {
                DateTime dateTime = this.getDateTime(new Date(), bookRule.getStopTime());
                if (dateTime.isBeforeNow()) {
                    item.setStatus(-1);
                }
            }
            if (page == pages && i == pageDateList.size() - 1) {
                item.setStatus(1);
            }
            bookingScheduleList.add(item);
        }
        Map<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosname",this.hospitalRepository.findByHoscode(hoscode).getHosname());
        baseMap.put("bigname",this.departmentRepository.findByHoscodeAndDepcode(hoscode,depcode).getBigname());
        baseMap.put("depname",departmentRepository.findByHoscodeAndDepcode(hoscode,depcode).getDepname());
        baseMap.put("workDateString",new DateTime().toString("yyyy年MM月"));
        baseMap.put("releaseTime",bookRule.getReleaseTime());
        baseMap.put("stopTime",bookRule.getStopTime());

        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleList", bookingScheduleList);
        result.put("total", total);
        result.put("baseMap", baseMap);
        return result;
    }

    private com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> getPageDateTime(Integer page, Integer limit, BookingRule bookRule) {


        Integer cycle = bookRule.getCycle();
        String releaseTime = bookRule.getReleaseTime();//查看是否已经到放号时间如果已经到放好时间了就cycle加1
        DateTime dateTime = this.getDateTime(new Date(), releaseTime);
        if (dateTime.isBeforeNow()) {
            //说明已经开始放号了cycle+1
            cycle += 1;
        }
        List<Date> allDateList = new ArrayList<>();
        //从今天开始创建连续的时间（yyyy-MM-dd）,没有时分秒，分页的话就截取
        for (int i = 0; i < cycle; i++) {
            Date date = new DateTime(new DateTime().plusDays(i).toString("yyyy-MM-dd")).toDate();
            allDateList.add(date);
        }
        int begin = (page - 1) * limit;
        int end = begin + limit;
        if (end > cycle) {
            end = cycle;
        }
        List<Date> pageDateList = new ArrayList<>();
        //开始截取分页list时间片段
        for (int i = begin; i < end; i++) {
            Date date = allDateList.get(i);
            pageDateList.add(date);
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Date> pageDate =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, limit, cycle);

        pageDate.setRecords(pageDateList);

        return pageDate;
    }


    private DateTime getDateTime(Date date, String releaseTime) {
        String s = new DateTime(date).toString("yyyy-MM-dd") + " " + releaseTime;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(s);

        return dateTime;
    }


    @Override
    public void remove(Map<String, String> map) {
        ackUtil.AckSign(map);
        String hoscode = map.get("hoscode");
        String hosScheduleId = map.get("hosScheduleId");
        Schedule hosSchedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (hosSchedule != null) {
            scheduleRepository.deleteById(hosSchedule.getId());
        }
    }

    @Override
    public Map<String, Object> getScheduleRoules(Integer pageNum, Integer pageSize, String hoscode, String depcode) {
        /*
        List<Schedule> schedules = scheduleRepository.findByHoscodeAndDepcode(hoscode, depcode);
        Map<Date, List<Schedule>> scheduleMap = schedules.stream().collect(Collectors.groupingBy(Schedule::getWorkDate));
        */

        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2 根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        //3 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                //排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //4 实现分页
                Aggregation.skip((pageNum - 1) * pageSize),
                Aggregation.limit(pageSize)
        );

        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();
        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();//总的日期个数

        //把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }


        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);
        result.put("total", total);

        return result;
    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        Date date = new DateTime(workDate).toDate();
        List<Schedule> scheduleList =
                scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, date);
        //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
        scheduleList.forEach(this::packageSchedule);
        return scheduleList;

    }

    @Override
    public Schedule getScheduleById(String id) {
        Optional<Schedule> byId = scheduleRepository.findById(id);
        Schedule schedule = byId.get();
    /*    String hoscode = schedule.getHoscode();
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, schedule.getDepcode());
        schedule.getParam().put("hosname",hospital.getHosname());
        schedule.getParam().put("depname",department.getDepname());*/
        this.packageSchedule(schedule);
        return schedule;
    }
    //提供给feign远程调用的接口
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {

        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = this.getScheduleById(scheduleId);
        if (schedule==null){
            throw  new DiyException(20001,"排班为空");
        }
        //获取预约规则信息
        Hospital hospital = hospitalService.getByHosCode(schedule.getHoscode());
        if (hospital==null){
            throw  new DiyException(20001,"查询医院为空");
        }

        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule==null){
            throw  new DiyException(20001,"预约规则为空");
        }

        //设置必要参数进去
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospital.getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname((String) schedule.getParam().get("depname"));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setAmount(schedule.getAmount());
        //退号截至天数，（就诊的前一天为-1，当天为0，以此类推）
        Integer quitDay = bookingRule.getQuitDay(); //quitDay = -1;
        DateTime quitTime = this.getDateTime(new
                DateTime(schedule.getWorkDate()).
                plusDays(quitDay).toDate(),bookingRule.getReleaseTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //获取预约开始时间
        DateTime startTime = this.getDateTime(new Date(),bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截至时间
        DateTime endTime = this.
                getDateTime(new DateTime()
                        .plusDays(bookingRule.getCycle())
                        .toDate(),bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(),bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }



    @Override
    public void update(Schedule schedule) {
        scheduleRepository.save(schedule);
    }


    @Autowired
    DepartmentService departmentService;

    @Autowired
    HospitalService hospitalService;

    private void packageSchedule(Schedule schedule) {

        //设置医院名称
        schedule.getParam().put("hosname",
                hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",
               departmentRepository.findByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());

        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",
                this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }


    //方法1
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    //方法2
    private String dayOfWeek(Date workDate) {
        DateTime dateTime = new DateTime(workDate);
        int dayOfWeek = dateTime.getDayOfWeek();//1:周一  2：周二   3：周三
        List<String> list = Arrays.asList("周一", "周二", "周三", "周四", "周五", "周六", "周日");
        return list.get(dayOfWeek - 1);
    }
}
